package com.mcptt.db.op;

import java.util.List;
import java.util.Vector;

import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.res.Resource;
import com.mcptt.comm.CommonFunc;
import com.mcptt.db.DBProvider;
import com.mcptt.db.DbConst;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.GroupInfo;
import com.mcptt.db.model.HistoryInfo;
import com.mcptt.db.model.SessionInfo;
import com.mcptt.db.model.UserInfo;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;

public class HistoryDbOperator
{

	public static String THIS_FILE = "DbOperator";
	private Context ctx = null;

	public HistoryDbOperator(Context ctx)
	{
		this.ctx = ctx;
	}

	public List<HistoryInfo> getHistoryInfoList()
	{
		ContentResolver cr = ctx.getContentResolver();
		List<HistoryInfo> list = new Vector<HistoryInfo>();
		Cursor cursor = null;
		try 
		{
			cursor = cr.query(DbConst.HISTORY_URI,
					DBProvider.HIRSTORY_FULL_PROJECTION, null,
					null,null );

			if (cursor == null
					|| cursor.getCount() <= 0)
			{
				return list;
			}
			while (cursor.moveToNext()) 
			{  
				HistoryInfo info = new HistoryInfo(cursor);  
				list.add(info);
			} 
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
			Log.debug(this.getClass(), "getGroupList e = " + e);
			e.printStackTrace();
		}
		finally
		{
			if(cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}

		return list;
	}

	public void insertNewSession(SessionInfo session, boolean isClear)
	{
		Log.debug(this.getClass(), "insertNewSession session =  " + session);
		ContentResolver cr = ctx.getContentResolver();
		cr.insert(DbConst.SESSION_URI, session.getContentValues());

		HistoryInfo hirstory = session.toHistoryInfo();
		//	String receiverUId = hirstory.getReceiver().getuId();
		String receiverNum = hirstory.getReceiver().getMcId();
		String selection = DbConst.COL_ReceiverNum + " =? ";

		Uri histroryUrl = ContentUris.withAppendedId(
				DbConst.HISTORY_ID_URI_BASE, 45);
		Cursor cursor = null;
		try
		{
			cursor = cr.query(histroryUrl, DBProvider.HIRSTORY_FULL_PROJECTION,
					selection, new String[]
							{ receiverNum }, null);

			if (cursor == null || cursor.getCount() <= 0)
			{
				Log.debug(this.getClass(), "insertNewSession insert ");
				cr.insert(DbConst.HISTORY_URI, hirstory.getContentValues());
			} else if (cursor != null && cursor.getCount() == 1)
			{
				cursor.moveToFirst();
				HistoryInfo info = new HistoryInfo(cursor);
				if (isClear)
				{
					hirstory.setUnreadCount(0);
				} else
				{
					//					int msgType = session.getMsgtype();
					//					if(msgType != SessionInfo.Msgtype_CallLog)
					{
						int oldUnreadCount = info.getUnreadCount();
						hirstory.setUnreadCount(oldUnreadCount + 1);
					}
				}
				Log.debug(this.getClass(), "insertNewSession hirstory = "
						+ hirstory);
				cr.update(DbConst.HISTORY_URI, hirstory.getContentValues(),
						selection, new String[]
								{ receiverNum });
			}
		} catch (Exception e)
		{
			// TODO: handle exception
		} finally
		{
			if (cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
	}

	public boolean delHirstory(boolean isGroup,String receiverUId)
	{
		Log.debug(this.getClass(), "delHirstory receiverUId =  " + receiverUId);
		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_ReceiverNum + " =? ";

		cr.delete(DbConst.SESSION_ID_URI_BASE, selection, new String[]
				{ receiverUId });
		int col = 0;
		if(isGroup)
		{
			ContentValues values = new ContentValues();
			String str = Resource.getString("history_clear");
			values.put(DbConst.COL_LastMsgContent, str);
			String data = CommonFunc.getDateAndTime();
			values.put(DbConst.COL_LastMsgDate, data);
			col =  cr.update(DbConst.HISTORY_ID_URI_BASE, values, selection,
					new String[]
							{ receiverUId });
		}
		else
		{
			col = cr.delete(DbConst.HISTORY_ID_URI_BASE, selection,
					new String[]
							{ receiverUId });
		}
		if (col > 0)
		{
			return true;
		}
		return false;
	}

	public boolean delAffiliationSession()//处理去守候功能
	{
		Log.debug(this.getClass(), "delAffiliationSession ");
		ContentResolver cr = ctx.getContentResolver();
		StringBuffer strBuf = new StringBuffer();
		//		strBuf.append(DbConst.COL_ReceiverNum).append(" =? and ");
		strBuf.append(DbConst.COL_Type).append(" =? ");

		String[] value = new String[]
				{""+SessionInfo.Msgtype_Affiliation};

		int col = cr.delete(DbConst.SESSION_ID_URI_BASE, strBuf.toString(),
				value);
		Log.debug(this.getClass(), "delAffiliationSession col = " + col);
		delAffiliationHirstory(cr);
		//		if (col > 0)
		//		{
		//			delAffiliationHirstory(cr);
		//			return true;
		//		}
		return false;
	}

	private void delAffiliationHirstory(ContentResolver cr)
	{
		Log.debug(this.getClass(), "DelAffiliationHirstory");

		//		String selection = DbConst.COL_Affiliation + " =? ";
		StringBuffer strBuf = new StringBuffer();
		strBuf.append(DbConst.COL_LastMsgType).append(" =? and ");
		strBuf.append(DbConst.COL_Affiliation).append(" =? ");

		int col =  cr.delete(DbConst.HISTORY_ID_URI_BASE, strBuf.toString(), new String[]
				{"10", "1" });
		Log.debug(this.getClass(), "DelAffiliationHirstory col = " + col);
	}

	public boolean delSession(SessionInfo info)
	{
		Log.debug(this.getClass(), "delSession SessionInfo =  " + info);
		if (info == null)
		{
			return false;
		}
		ContentResolver cr = ctx.getContentResolver();
		StringBuffer strBuf = new StringBuffer();
		strBuf.append(DbConst.COL_ReceiverNum).append(" =? and ");
		strBuf.append(DbConst.COL_SenderId).append(" =? and ");
		strBuf.append(DbConst.COL_MsgType).append(" =? and ");
		strBuf.append(DbConst.COL_Direction).append(" =? and ");
		strBuf.append(DbConst.COL_Date).append(" =? ");

		//	String receiverUId = info.getReceiver().getuId();
		String receiverNum = info.getReceiver().getMcId();
		//	String senderUId = info.getSender().getuId();
		String senderNum = info.getSender().getMcId();
		String[] value = new String[]
				{ receiverNum, senderNum,""+info.getMsgtype(), "" + info.getDirection(), info.getDate() };

		int col = cr.delete(DbConst.SESSION_ID_URI_BASE, strBuf.toString(),
				value);
		if (col > 0)
		{
			updateOrDelHirstory(cr, receiverNum);
			return true;
		}
		return false;
	}

	private void updateOrDelHirstory(ContentResolver cr, String receiverNum)
	{
		Log.debug(this.getClass(), "updateOrDelHirstory receiverNum = "
				+ receiverNum);
		String selection = DbConst.COL_ReceiverNum + " =? ";
		Cursor cursor = cr.query(DbConst.SESSION_ID_URI_BASE,
				DBProvider.SESSION_FULL_PROJECTION, selection, new String[]
						{ receiverNum }, null);
		if (cursor == null || cursor.getCount() == 0)
		{
			cr.delete(DbConst.HISTORY_ID_URI_BASE, selection, new String[]
					{ receiverNum });
			Log.debug(this.getClass(), "updateOrDelHirstory delete");
		} else
		{
			int count = cursor.getCount();
			Log.debug(this.getClass(),
					"updateOrDelHirstory cursor.getCount() = " + count);
			if (cursor.moveToLast())
			{
				int index = cursor.getColumnIndex(DbConst.COL_Content);
				String content = cursor.getString(index);
				Log.debug(this.getClass(), "updateOrDelHirstory content =  "
						+ content);
				ContentValues values = new ContentValues();
				values.put(DbConst.COL_LastMsgContent, content);
				cr.update(DbConst.HISTORY_ID_URI_BASE, values, selection,
						new String[]
								{ receiverNum });
			}
			Log.debug(this.getClass(), "cursor.moveToLast() false");
		}
		cursor.close();
	}

	public void resetSessionCount(AddrInfo curUserInfo)
	{
		Log.debug(this.getClass(), "resetMsgCount curUserInfo = " + curUserInfo);
		if (curUserInfo == null)
		{
			return;
		}
		//	String receiverUId = curUserInfo.getuId();
		String receiverNum = curUserInfo.getMcId();

		ContentResolver cr = ctx.getContentResolver();
		ContentValues cv = new ContentValues();

		String selection = DbConst.COL_ReceiverNum + " =? ";
		cv.put(DbConst.COL_UnreadCount, "0");
		cr.update(DbConst.HISTORY_URI, cv, selection, new String[]
				{ receiverNum });
	}

	public boolean hasNewMsg()
	{
		Log.debug(this.getClass(), "hasNewMsg");
		boolean result = false;
		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_UnreadCount + "!=?";

		Uri histroryUrl = ContentUris.withAppendedId(
				DbConst.HISTORY_ID_URI_BASE, 45);

		Cursor cursor = null;
		try
		{
			cursor = cr.query(histroryUrl, DBProvider.HIRSTORY_FULL_PROJECTION,
					selection, new String[]
							{ "0" }, null);

			if (cursor != null && cursor.getCount() > 0)
			{
				Log.debug(this.getClass(), "hasNewMsg cursor.getCount() = "
						+ cursor.getCount());
				result = true;
			}
		} catch (Exception e)
		{
			// TODO: handle exception
		} finally
		{
			if (cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
		return result;
	}

	public UserInfo getUserInfoByNum(String mcId)
	{
		Log.debug(this.getClass(), "getUIdByNum mcId = " + mcId);
		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_Id + "= ?";
		Cursor cursor = null;
		try
		{
			cursor = cr.query(DbConst.ADDRESS_URI,
					DBProvider.ADDRESS_FULL_PROJECTION, selection, new String[]
							{ "" + mcId }, null);

			if (cursor != null && cursor.getCount() == 1)
			{
				cursor.moveToFirst();
				UserInfo info = new UserInfo(cursor);
				return info;
			}
		} catch (Exception e)
		{
			// TODO: handle exception
		} finally
		{
			if (cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
		return new UserInfo(mcId);
	}
	
	public GroupInfo getGroupInfoByNum(String num)
	{
		Log.debug(this.getClass(), "getGroupInfoByNum num = " + num);
		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_Id + "= ?";
		Cursor cursor = null;
		try
		{
			cursor = cr.query(DbConst.GROUP_ADDRESS_URI,
					DBProvider.GROUP_ADDRESS_FULL_PROJECTION, selection, new String[]
							{ "" + num }, null);

			if (cursor != null && cursor.getCount() == 1)
			{
				cursor.moveToFirst();
				GroupInfo info = new GroupInfo(cursor);
				return info;
			}
		} catch (Exception e)
		{
			// TODO: handle exception
		} finally
		{
			if (cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
		return null;
	}
}
